package honeypot.yhgl.action;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import honeypot.yhgl.pojo.User;
import cm.util.action.info.GenericInfoActionSupport;
import cm.util.exception.MessageException;
import cm.util.hibernate.HibernateSessionFactory;

public class UserInfoAction extends GenericInfoActionSupport<User> {
	    /**
	 * 
	 */
	private static final long serialVersionUID = 6335930897281515026L;
		private Session session;
	    private Transaction trans;
	    private String hql;
	    private Query query;
	    private Double username_num;
	    
		public Session getSession() {
			return session;
		}

		public void setSession(Session session) {
			this.session = session;
		}

		public Transaction getTrans() {
			return trans;
		}

		public void setTrans(Transaction trans) {
			this.trans = trans;
		}

		public String getHql() {
			return hql;
		}

		public void setHql(String hql) {
			this.hql = hql;
		}

		public Query getQuery() {
			return query;
		}

		public void setQuery(Query query) {
			this.query = query;
		}

		public UserInfoAction() {
			super(User.class);
		}

		public Double getUsername_num() {
			return username_num;
		}

		public void setUsername_num(Double usernameNum) {
			username_num = usernameNum;
		}

		@Override
		public String add() throws MessageException {
			
			getEntity().getUsername();
			getEntity().getPassword();
			System.out.println(getEntity().getUsername().length());
			System.out.println(getEntity().getPassword().length());
			 if(getEntity().getUsername().length()==0)
			   {
				 this.addFieldError("用户名","用户名不能为空!");
			      return "false";
			    }
			   else if(getEntity().getUsername().length()<6||getEntity().getUsername().length()>10)
			   {
				  this.addFieldError("用户名","用户名长度应该在6到10之间!");
			      return "false";
				  }

			   if(getEntity().getPassword().length()==0)
			   {
				   this.addFieldError("密码","密码不能为空!");
			      return "false";
			    }
			   else if(getEntity().getPassword().length()<6||getEntity().getPassword().length()>10)
			   {
				   this.addFieldError("密码","密码长度应该在6到10之间!");
			      return "false";
				}
			      session=HibernateSessionFactory.getSession();
				  trans=session.beginTransaction();
				  hql="select count(*) from User where username=:t";
				  query=session.createQuery(hql);
				  query.setString("t", getEntity().getUsername());//设置查询参数
				  username_num=Double.parseDouble(query.iterate().next().toString());  
				  System.out.println("username为"+getEntity().getUsername()+"的用户数量为"+username_num);
				  
				  if(username_num>0.5)
				  {
					  this.addFieldError("username","username has been existed!");
					  
					  return "false";
				  }				 
				  
				  session.close();

			return super.add();
		}
	

}
